<html>
<head><title>CS 143 Project 1B</title></head>
<body>

Type an SQL query into the following box:

<form action="query.php" method="GET">
<textarea name="query" cols="60" rows="8"><?php echo $_GET['query']; ?></textarea>
<input type="submit" value="Submit" />
</form>

<?php

$userquery = $_GET['query'];
if ($userquery) {
    // Open connection to the database
    $dbconn = mysql_connect("localhost", "cs143", "");
    if (!$dbconn) {
        $errmsg = mysql_error($dbconn);
        echo "Connection failed: $errmsg<br />\n";
        exit(1);
    }
    
    // Select the database to use
    mysql_select_db("CS143", $dbconn);
    
    // Issue query
    $query_result = mysql_query($userquery, $dbconn);
    if (!$query_result) {
        echo "Query error: " . mysql_error() . "<br />\n";
        exit(1);
    }
    
    // Output results
    echo "<h3>Query result:</h3>\n";
    echo "<table border=\"1\">\n";
    
    // Output table headers
    $nfields = mysql_num_fields($query_result);
    
    echo "<tr>";
    for ($i = 0; $i < $nfields; $i++) {
        echo "<th>" . mysql_field_name($query_result, $i) . "</th>\n";
    }
    echo "</tr>";
    
    // For each row in the result, output it as a table row
    while ($row = mysql_fetch_row($query_result)) {
        echo "<tr>";
        // Output each element in a row
        for ($i = 0; $i < count($row); $i++) {
            $el = $row[$i];
            
            // If element is NULL, set it as N/A
            if (!$el)
                $el = "N/A";
                
            echo "<td>$el</td>";
        }
        echo "</tr>\n";
    }
    
    echo "</table>\n";
    
    // Close connection
    mysql_close($dbconn);
     
}

?>

</body>
</html>